package com.bootdo.ocr.xfyun;

import com.alibaba.fastjson.JSON;
import com.bootdo.ocr.FileUrlDTO;
import com.bootdo.ocr.OcrService;
import com.bootdo.ocr.xfyun.api.XunFeiYunClient;
import com.bootdo.ocr.xfyun.dto.BlockObj;
import com.bootdo.ocr.xfyun.dto.XfYunOcrResult;
import com.bootdo.utils.PDFToIMGUtil;
import com.google.common.collect.Lists;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XfYunOcrService extends OcrService<XfYunOcrResult> {

    private XunFeiYunClient client;

    public XfYunOcrService(String apiKey, String appId) {
        this.init( apiKey, null,  appId);
    }

    @Override
    protected void init(String apiKey, String secretKey, String appId) {
        this.appId = appId;
        this.apiKey = apiKey;
        this.secretKey = secretKey;
        client = new XunFeiYunClient(appId, apiKey);
    }

    @Override
    protected List<XfYunOcrResult> fetchOcrDataByFileUrlDTO(FileUrlDTO dto) {
        final Map<String, String> filePathMap = dto.getFilePathMap();
        List<XfYunOcrResult> results = Lists.newLinkedList();
        Map<String, XfYunOcrResult> resultMap = new HashMap<>();
        for (String sourcePath : filePathMap.keySet()) {
            String  res = null;
           try {
               // 调用接口
               String path = filePathMap.get(sourcePath);
               res = client.fetchOcrApi(path);
               logger.debug("data =============>>>>>> " + res);
               final String[] split = path.split("\\\\");
               final XfYunOcrResult xfyunOcrResult = tranJsonBean(res, XfYunOcrResult.class);

               final String fileName = split[split.length - 1].replace(".png", "");
               xfyunOcrResult.setFileName(fileName);
               xfyunOcrResult.setFilePath(sourcePath);
               resultMap.put(sourcePath, xfyunOcrResult);
               if(validateDoRepeat(xfyunOcrResult)){
                   dto.getFailFilePathMap().put(sourcePath, filePathMap.get(sourcePath));
               }
           } catch (Exception e) {
               logger.error("xunfei fetchOcrDataByFileUrlDTO decode error ====== >>>>>>" + res, e);
               dto.getFailFilePathMap().put(sourcePath, filePathMap.get(sourcePath));
           }
        }
        logger.info("cover data " + JSON.toJSONString(results));

        roundRobinApi(dto, 1, resultMap);

        results.addAll(resultMap.values());
        results.forEach(obj -> obj.matchCode(dto.getPattern()));
        return results;
    }

    /**
     * 校验是否重新处理
     * @param xfyunOcrResult 处理结果
     * @return boolean
     */
    protected boolean validateDoRepeat(XfYunOcrResult xfyunOcrResult) {

        if (xfyunOcrResult.getData() == null
                || xfyunOcrResult.getData().getBlock() == null) {
            return true;
        }
        List<BlockObj> blockObjs = xfyunOcrResult.getData().getBlock();
        for (BlockObj blockObj : blockObjs) {
            if (blockObj.getLine() == null
                    || blockObj.getLine().size() == 0) {
                return true;
            }
        }
        return false;
    }
    /**
     * 递归5次 调用还是失败就不管了
     * @param dto
     * @param pollIndex
     * @param resultMap
     */
    @Override
    protected void roundRobinApi(FileUrlDTO dto, int pollIndex,  Map<String, XfYunOcrResult> resultMap) {
        final Map<String, String> failFilePathMap = dto.getFailFilePathMap();
        if (failFilePathMap.size() > 0) {
            for (String sourcePath : failFilePathMap.keySet()) {
                String  res = "";
                try {
                    PDFToIMGUtil.pdf2PngPath(sourcePath, failFilePathMap.get(sourcePath), DPIVAL_MAP.get(pollIndex));
                    String path = failFilePathMap.get(sourcePath);
                    res = client.fetchOcrApi(path);
                    final String[] split = path.split("\\\\");
                    final XfYunOcrResult xfyunOcrResult = tranJsonBean(res, XfYunOcrResult.class);
                    final String fileName = split[split.length - 1].replace(".png", "");
                    xfyunOcrResult.setFileName(fileName);
                    xfyunOcrResult.setFilePath(sourcePath);
                    resultMap.put(sourcePath, xfyunOcrResult);
                    /**
                     * 查看是否需要重新处理,可能png是空白
                     */
                    if(validateDoRepeat(xfyunOcrResult)) {
                        dto.getFailFilePathMap().put(sourcePath, path);
                    } else {
                        failFilePathMap.remove(sourcePath);
                    }
                } catch (Exception e) {
                    logger.error("xunfei pollApi decode error ====== >>>>>>" + res, e);
                }
            }
            pollIndex ++;
            if (pollIndex <= POLL_TIME  && dto.getFailFilePathMap().size() > 0) {
                roundRobinApi(dto, pollIndex, resultMap);
            }
        }

    }

}
